package com.eet.order.service.impl;

import com.eet.order.constants.CommonConstants;
import com.eet.order.service.OrderService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 订单服务实现类
 *
 * @author zheng.zhang
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public String makeFanoutOrder(String userId, String productId, int orderNum) {
        String orderId = getOrderId();
        // 通过MQ完成消息分发
        rabbitTemplate.convertAndSend(CommonConstants.FANOUT_EXCHANGE, CommonConstants.EMPTY, orderId);
        return orderId;
    }

    /**
     * 获取订单ID
     *
     * @return 订单ID
     */
    private String getOrderId() {
        // 判断库存
        String orderId = UUID.randomUUID().toString();
        // 生成订单
        System.out.println("订单生成成功: " + orderId);
        return orderId;
    }

    @Override
    public String makeDirectOrder(String userId, String productId, int orderNum) {
        String orderId = getOrderId();
        // 邮件
        rabbitTemplate.convertAndSend(CommonConstants.DIRECT_EXCHANGE, CommonConstants.EMAIL, orderId);
        // 短信
        rabbitTemplate.convertAndSend(CommonConstants.DIRECT_EXCHANGE, CommonConstants.SMS, orderId);
        return orderId;
    }

    @Override
    public String makeTopicOrder(String routeingKey, String productId, int orderNum) {
        String orderId = getOrderId();
        // 发送消息
        rabbitTemplate.convertAndSend(CommonConstants.TOPIC_EXCHANGE, routeingKey, orderId);
        return orderId;
    }

    @Override
    public String makeDeadOrder(String userId, String productId, int orderNum) {
        String orderId = getOrderId();
        // 发送消息到过期队列中
        rabbitTemplate.convertAndSend(CommonConstants.TTL_DIRECT_EXCHANGE, CommonConstants.TTL, orderId);
        return orderId;
    }
}
